package common.tools;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class StringTool {
	private static Logger logger = LoggerFactory.getLogger(StringTool.class);

	
	/**  
     * 匹配中国邮政编码  
     * @param postcode 邮政编码  
     * @return 验证成功返回true，验证失败返回false  
     */   
    public static boolean isPostCode(String postCode){  
        String reg = "[1-9]\\d{5}";  
        return Pattern.matches(reg, postCode);  
    }  
	
    
    /**  
     * 验证密码格式 
     * @param  
     * @return 验证成功返回true，验证失败返回false  
     */   
    public static boolean isPassword(String password){  
        String reg = "[0-9]+[a-zA-Z]+[0-9a-zA-Z]*|[a-zA-Z]+[0-9]+[0-9a-zA-Z]*";  
        return Pattern.matches(reg, password);  
    }  
	/** 
     * 功能：验证字符串长度是否符合要求，一个汉字等于两个字符
     * @param strParameter 要验证的字符串
     * @param limitLength 验证的长度
     * @return 符合长度ture 超出范围false
     */
    public static boolean validateStrByLength(String strParameter ,int  minLength,int maxLength){
         int temp_int=strParameter.length();
//         byte[] b=strParameter.getBytes();
//      for(int i=0 ; i<b.length ; i++){
//         if(b[i]>=0){
//            temp_int=temp_int+1;
//          }else{
//             temp_int=temp_int+2;
//             i++;
//          }
//     }
     if(temp_int > maxLength||temp_int<minLength){
        return false;
         }else{
        return true;
      }
  }
	
	/** 
     * 分页排序字段拼接 
     *  
     * @param  str 
     * @return 验证通过返回true 
     */ 
	public static String joinSortFieldOrder(String filed,String sord){
		StringBuffer orderFiled = new StringBuffer();
		if(!StringTool.isEmpty(filed)){
			orderFiled.append(filed);
			if(!StringTool.isEmpty(sord)){
				orderFiled.append(" ").append(sord);
			}
		}
		return orderFiled.toString();
	}

	/** 
     * 手机号验证 
     *  
     * @param  str 
     * @return 验证通过返回true 
     */  
    public static boolean isMobile(String str) {   
        Pattern p = null;  
        Matcher m = null;  
        boolean b = false;   
        p = Pattern.compile("^1[0-9]{10}$"); // 验证手机号  
        m = p.matcher(str);  
        b = m.matches();   
        return b;  
    }  
    /** 
     * 电话号码验证 
     *  
     * @param  str 
     * @return 验证通过返回true 
     */  
    public static boolean isPhone(String str) {   
        Pattern p1 = null,p2 = null;  
        Matcher m = null;  
        boolean b = false;    
        p1 = Pattern.compile("^[0][1-9]{2,3}-[0-9]{5,10}$");  // 验证带区号的  
        p2 = Pattern.compile("^[1-9]{1}[0-9]{5,8}$");         // 验证没有区号的  
        if(str.length() >9)  
        {   m = p1.matcher(str);  
            b = m.matches();    
        }else{  
            m = p2.matcher(str);  
            b = m.matches();   
        }    
        return b;  
    } 
    /** 
     * 是否有乱码验证 
     *  
     * @param  strName 
     * @return 有返回true 
     */
    public static boolean isMessyCode(String strName) {
        try {
            Pattern p = Pattern.compile("\\s*|\t*|\r*|\n*");
            Matcher m = p.matcher(strName);
            String after = m.replaceAll("");
            String temp = after.replaceAll("\\p{P}", "");
            char[] ch = temp.trim().toCharArray();

            int length = (ch != null) ? ch.length : 0;
            for (int i = 0; i < length; i++) {
                char c = ch[i];
                if (!Character.isLetterOrDigit(c)) {
                    String str = "" + ch[i];
                    if (!str.matches("[\u4e00-\u9fa5]+")) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }
	/**
	 * 判断用户名的合法性
	 * 
	 */
	public static boolean checkUserName(String name) { // 检查用户名的合法性
		byte[] temp = name.getBytes();
		boolean result = true;
		int length;
		// System.out.println("name="+name);
		if (temp[0] > 47 && temp[0] < 58) { // 判断用户名第一个字符不能为数字
			result = false;
		} else {
			length = temp.length;
			if (length > 0 && length < 18) { // 判断用户名的长度
				for (int i = 0; i < temp.length; i++) {
					if (!((temp[i] > 47 && temp[i] < 58) || (temp[i] > 64 && temp[i] < 91)
							|| (temp[i] > 96 && temp[i] < 123))) { // 判断用户名是否在合法字符内
						result = false;
						break; // 终止循环退出
					}
				}
			} else {
				result = false;
			}
		}

		return result;
	}
	
	public static boolean isStringAvaliable(String string) {
		return string != null && !"".equals(string.trim());
	}
	public static boolean isEmpty(String str) {
		return !isStringAvaliable(str);
	}

	/**
	 * 判断字符串是否有中文
	 * 
	 * 
	 */
	// GENERAL_PUNCTUATION 判断中文的“号
	// CJK_SYMBOLS_AND_PUNCTUATION 判断中文的。号
	// HALFWIDTH_AND_FULLWIDTH_FORMS 判断中文的，号
	private static final boolean isChinese(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
				|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
				|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
				|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
			return true;
		}
		return false;
	}

	public static final boolean isChinese(String strName) {
		char[] ch = strName.toCharArray();
		for (int i = 0; i < ch.length; i++) {
			char c = ch[i];
			if (isChinese(c)) {
				return true;
			}
		}
		return false;
	}
	
	/*判断字符串格式是否符合日期格�?*
	@param st �?要检查的字符�?
	 * @return boolean  格式正确返回true**/

	public static boolean validateDate(String st) {
		if (st.length() != 8)
			return false;
		String year = st.substring(0, 4);
		String month = st.substring(4, 6);
		String day = st.substring(6, 8);
		int d, m, y;
		try {
			d = Integer.parseInt(day);
			m = Integer.parseInt(month);
			y = Integer.parseInt(year);
		} catch (NumberFormatException nfe) {
			return false;
		}
		if (m < 1 || m > 12) {
			return false;
		}
		if (d < 1 || d > 31) {
			return false;
		}
		if ((m == 4 || m == 6 || m == 9 || m == 11) && (d == 31)) {
			return false;
		}
		if (m == 2) {
			boolean leap = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0));
			if (d > 29 || (d == 29 && !leap)) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 判断字符串是否为数字
	 * 
	 * */
	public static boolean checkingNumber(String moving){
		if(moving.matches("[0-9]+")){
			return true;
		} 
		return false;
	}

	/**
	 * 根据身份证判断�?�别
	 * 
	 * @param cardNumber
	 *            证件号码
	 * @return -1�?? 身份证格式不正确 0：女 1：男
	 * */
	public static int DecideSexByCard(String cardNumber) {
		if (cardNumber != null) {
			String sex = null;
			if (cardNumber.length() == 15) {
				sex = cardNumber.substring(14, 15);
			} else if (cardNumber.length() == 18) {
				sex = cardNumber.substring(16, 17);
			}
			if (sex != null && stringIsNumber(sex)) {
				if (isOddOrEven(Integer.parseInt(sex)).equals("1")) {
					return 1;
				} else if (isOddOrEven(Integer.parseInt(sex)).equals("2")) {
					return 0;
				}
			}
		}
		return -1;
	}

	/**
	 * 根据身份证返回出生日�?
	 * 
	 * @param cardNumber
	 *            证件号码
	 * @return -1 身份证格式不正确     YYYY-MM-DD
	 * */
	public static String DecideBirthdayByCard(String cardNumber) {
		if (cardNumber != null) {
			if (cardNumber.length() == 15) {
				String year = cardNumber.substring(5, 7);
				String mm = cardNumber.substring(7, 9);
				String dd = cardNumber.substring(9, 11);
				if(!dataString("19"+year+mm+dd))return "-1";
				return "19"+year+"-"+mm+"-"+dd;
			} else if (cardNumber.length() == 18) {
				String year = cardNumber.substring(6, 10);
				String mm = cardNumber.substring(10, 12);
				String dd = cardNumber.substring(12, 14);
				if(!dataString(year+mm+dd))return "-1";
				return year+"-"+mm+"-"+dd;
			}
			
		}
		return "-1";
	}

	/**
	 * 校验18位的身份证是否合�??
	 * 
	 * */
	public static boolean isIdCard(String arrIdCard) {
		int sigma = 0; 
		Integer[] a = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
		String[] w = { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" };
		if (arrIdCard.length() != 18) {
			if (arrIdCard.length() == 15) {
				return true;
			}
			return false;
		}
		for (int i = 0; i < 17; i++) {
			int ai = Integer.parseInt(arrIdCard.substring(i, i + 1));
			int wi = a[i];
			sigma += ai * wi;
		}
		int number = sigma % 11;

		String check_number = w[number];
		// return check_number;
		// logger.error(arrIdCard.substring(17).toLowerCase());
		if (!arrIdCard.substring(17).toUpperCase().equals(check_number)) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 判断字符串是否为数字(正数)
	 * 
	 * @param string
	 *            �??要校验的字符�??
	 * @return boolean 是数字返回true 非数字返�?? false
	 * */
	public static boolean stringIsNumber(String string) {
		if (string.matches("[0-9]+")) {
			return true;
		}
		return false;
	}

	/**
	 * 判断字符串是否为数字(支持小数�?)
	 * 
	 * @param string
	 *            �??要校验的字符�??
	 * @return boolean 是数字返回true 非数字返�?? false
	 * */
	public static boolean number(String st) {
		if (st.matches("[0-9]+"))
			return true;
		if (st.matches("[0-9]+[.][0-9]"))
			return true;
		if (st.matches("[0-9]+[.][0-9][0-9]"))
			return true;
		if (st.matches("[0-9]+[.][0-9][0-9][0-9]"))
			return true;
		if (st.matches("[0-9]+[.][0-9][0-9][0-9][0-9]"))
			return true;
		return false;
	}

	/**
	 * 判断�??个数为奇数还是偶�??
	 * 
	 * @param number
	 *            �??要校验的数字
	 * @return String 1代表正数奇数 2代表正数偶数 -1代表负数的奇�?? -2代表负数的偶�??
	 * */
	public static String isOddOrEven(int number) {
		if (number >= 0) {
			if (number % 2 == 0) {
				return "2";
			} else {
				return "1";
			}
		} else {
			if (number % 2 == 0) {
				return "-2";
			} else {
				return "-1";
			}
		}
	}

	/**
	 * 判断�??个日期是否在指定年限以内
	 * 
	 * @param data
	 *            �??要校验的时间
	 * @param number
	 *            指定的年�??
	 * @return boolean true 指定年限之前 false 不在指定年限之前
	 * */
	public static boolean isBeforenumber(Date date, int number) {
		Date date1 = countDateYear(number);
		return date.after(date1);
	}

	/**
	 * 判断字符串日期是否合法（yyyymmdd�?? 不足时有补零满足长度
	 * */
	public static boolean dataString(String st) {
		if (st.length() != 8)
			return false;
		String year = st.substring(0, 4);
		String month = st.substring(4, 6);
		String day = st.substring(6, 8);
		int d, m, y;
		try {
			d = Integer.parseInt(day);
			m = Integer.parseInt(month);
			y = Integer.parseInt(year);
		} catch (NumberFormatException nfe) {
			return false;
		}
		if (m < 1 || m > 12) {
			return false;
		}
		if (d < 1 || d > 31) {
			return false;
		}
		if ((m == 4 || m == 6 || m == 9 || m == 11) && (d == 31)) {
			return false;
		}
		if (m == 2) {
			boolean leap = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0));
			if (d > 29 || (d == 29 && !leap)) {
				return false;
			}
		}
		return true;

	}

	/**
	 * 
	 * @param date1 yyyymmdd 出生日期
	 * @param date2 yyyymmdd 投保日期
	 * @param no  date1 是不是在date2的date年前   
	 * @return date2减去date1等于或大于no 返回false 或�?�date1非法返回false   
	 *    
	 */
	 public static boolean dateTool(String date1,String date2,int no){
		 try {
		 if(!dataString(date1)){
			 return false;
		 }
		 SimpleDateFormat sdf = new SimpleDateFormat();
		sdf.applyPattern("yyyyMMdd");
		Date birth = sdf.parse(date1);
		Date tbDate = null;
		 if(dataString(date2)){
			 tbDate = sdf.parse(date2);
		 } else {
			 tbDate = new Date();
		 }
		     Calendar c = Calendar.getInstance();
			c.setTime(tbDate);
			c.add(Calendar.YEAR, no);
			Date tbDate_tep = c.getTime();// 返回结果
			return tbDate_tep.before(birth);
		 } catch (ParseException e) {
				return false;
		}
	 }

	/**
		 * 当前日期减去(或加�??)指定的年�??
		 * */
		public static Date countDateYear(int year) {
			Calendar c = Calendar.getInstance();
			c.setTime(new Date());
			c.add(Calendar.YEAR, year);
			Date d = c.getTime();// 返回结果
			return d;
		}

	/**
	 * 计算两个日期相差的年�?
	 * @param  st1  出生日期
	 * @param  st2  当前日期
	 * 1、格式不正确返回 0
	 * 
	 * */
	public static int get1(String st1,String st2){
        if(validateDate(st1) && validateDate(st2)){
        	 int year1 = Integer.parseInt(st1.substring(0,4));
    		 int year2 = Integer.parseInt(st2.substring(0,4));
    		 String stEnd1 = year2+st1.substring(4,st1.length());
    		 Date date1 = DateTimeTool.toDate5(stEnd1);
     		 Date date2 = DateTimeTool.toDate5(st2);
             if(date1.before(date2)){
            	 return (year2-year1);
             } else {
            	return (year2-year1)-1;
             }
		}
		return -1;
	}

	// 去掉非数字（包括小数点）
	public static String getNumberString(String st){
		if(st !=null){
			return st.replaceAll("[\\D]+", "");
		}
		return null;
	}

	// 去掉非数字（不包括小数点�?
	public static String getNumberString2(String st){
		if(st !=null){
			 st = st.replaceAll("[\u4E00-\u9FFF]", "");
			 st = st.replaceAll("[a-zA-Z]+", ""); 
			 st = st.replaceAll("[${}\\/,�?%^!~@#$%&*():''\"\"-+=|]", ""); 
			 
			return st;
			
		}
		return null;
	}

	// 去掉非数字（不包括小数点 和^�?
	public static String getNumberString3(String st){
		if(st !=null){
			 st = st.replaceAll("[\u4E00-\u9FFF]", "");
			 st = st.replaceAll("[a-zA-Z]+", ""); 
			 st = st.replaceAll("[{}\\/,�?%!~@#%&*():''\"\"-+=|]", ""); 
			 
			return st;
			
		}
		return null;
	}

	// 去掉非数字（不包括符号）
	public static String getNumberString3_2(String st){
		if(st !=null){
			 st = st.replaceAll("[\u4E00-\u9FFF]", "");
			 st = st.replaceAll("[a-zA-Z]+", ""); 
			return st;
			
		}
		return null;
	}

	// 去掉非中�?
	public static String clearNotChinese(String buff){

	      String tmpString =buff.replaceAll("(?i)[^a-zA-Z0-9\u4E00-\u9FA5]", "");//去掉�?有中英文符号
	     char[] carr = tmpString.toCharArray();
	     
	     for(int i = 0; i<tmpString.length();i++){
	      if(carr[i] < 0xFF){
	       carr[i] = ' ' ;//过滤掉非汉字内容
	      }
	      
	     }
	     return String.copyValueOf(carr).trim();
	      }

	// 判断字符串是否是邮件地址（含中文，默认非法）
	public static boolean isEmail(String st){
		 if(!st.matches("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*")){
			 return false;
		 }
		 return true;
	 }

	/**
	  * 将一转换�?1
	  * 
	  * */
	 
	 public static String chZhuannumber(String st){
		 st = st.replace("�?","1");
		 st = st.replace("�?","2");
		 st = st.replace("�?","3");
		 st = st.replace("�?","4");
		 st = st.replace("�?","5");
		 st = st.replace("�?","6");
		 st = st.replace("�?","7");
		 st = st.replace("�?","8");
		 st = st.replace("�?","9");
		 st = st.replace("�?","10");
		 return st;
	 }

	/**
		 * 转全角的函数(SBC case)
		 * 
		 * 
		 * */
		public static String ToSBC(String input) {
			if(input == null) return "";
			// 半角转全角：
			char[] c = input.toCharArray();
			for (int i = 0; i < c.length; i++) {
				if (c[i] == 32) {
					c[i] = (char) 12288;
					continue;
				}
				if (c[i] < 127)
					c[i] = (char) (c[i] + 65248);
			}
			return new String(c);
		}

	/**/// /
	// / 转半角的函数(DBC case)
	// /
	// /任意字符�?
	// /半角字符�?
	// /
	// /全角空格�?12288，半角空格为32
	// /其他字符半角(33-126)与�?�试.大提示全�?(65281-65374)的对应关系是：均相差65248
	// /
	/**
		 * 转半角的函数(DBC case)
		 * 
		 * 
		 * */
		public static String ToDBC(String input) {
			if(input == null) return "";
			char[] c = input.toCharArray();
			for (int i = 0; i < c.length; i++) {
				if (c[i] == 12288) {
					c[i] = (char) 32;
					continue;
				}
				if (c[i] > 65280 && c[i] < 65375)
					c[i] = (char) (c[i] - 65248);
			}
			return new String(c);
		}

	// 判断字符�? 字符长度 是否大于指定长度
	public static boolean isCharVar(String in,int charInt){
		if(in == null) return false;
		int sum = 0;
		for (int i = 0; i < in.length(); i++) {
			if (19968 < in.charAt(i) && in.charAt(i) < 40869) {
				sum += 2;
			} else {
				sum += 1;
			}
		}
		
		if(sum >= charInt)return true; 
		
		return false;
	}

	/**
	  * 将字符串数组增加到一样长�?
	  * st1 �?要变长的
	  * st2 作为标准�?
	  * */
	 public static String[] getStringLis(String[] st1,String[] st2){
		 if(st1.length>=st2.length){
			 return st1;
		 }
		 String[] st = new String[st2.length];
		 for(int r=0;r<st2.length;r++){
			try{
				st[r]=st1[r];
			}catch (Exception e) {
				st[r]="";
			}
		 }
		 return st;
	 }

	/**
	  * 字符串四舍五�?
	  * 
	  * */
	 public static String siswr(String st){
		 if(number(st)){
			 double f = Double.valueOf(st);
			 return (int)Math.round(f)+""; 
			}
		 return "";
	 }

	public static String defaultString(String st){
		 if(st == null){
			 return "";
		 }
		 return st;
	 }

	public static String getGaoziY(String yn,int nu){
		 yn = yn.replace("�?",",");
		 
		 String[] sts = yn.split(",");
		 String newyn1 = sts[0];
		 for(int r=1;r<sts.length;r++){
			 newyn1 =newyn1+","+sts[r];
		 }
		 
		 yn = newyn1;
		 
		 logger.error(""+sts.length);
		 if(sts.length != nu&&!yn.endsWith(",")){
			 if(sts.length<nu){
				 for(int r=0;r<(nu-sts.length);r++){
					 yn =yn+",";
				 }
			 } else {
				 String newyn = sts[0];
				 for(int r=1;r<nu;r++){
					 newyn =newyn+","+sts[r];
				 }
				 yn = newyn;
			 }
		 }
		 
		 return yn;
	 }

	public static String getBaoz(String old){
		 String num = getNumberString3(old);
		 if(num.equals(""))return "";
		 
		 int ind =old.indexOf(num);
		 if(ind == -1) return "";
		 
		 String nes = old.substring(ind, old.length());
		 if(nes.contains("�?")){
			 return num+"y";
		 } else if(nes.contains("�?")){
			 return num+"a";
		 }
		 
		 return "";
	 }

	public static void main(String[] args) {
		//System.out.println(getNumberString3_2("追加180000"));
	}
}
